import { Injectable, Dependencies, ExecutionContext } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { ROLES_KEY } from 'src/modules/action/descriptor/function.descriptoor';

@Injectable()
@Dependencies(Reflector)
export class RolesGuard {
    constructor(
        private reflector: Reflector
    ) { }

    canActivate(context: ExecutionContext) {
       
        const { user } = context.switchToHttp().getRequest();
        const requiredRoles = this.reflector.getAllAndOverride(ROLES_KEY, [
            context.getHandler(),
            context.getClass(),
        ]);
        if (!requiredRoles) {
            return true;
        }
        
        return requiredRoles.some((role) => user.roles.includes(role));
    }
}